package com.plm.blogs.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.plm.blogs.utils.ResultMsg;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author Limi
 * @create 2019-01-10 18:51
 */
@RestController
@RequestMapping("/code")
public class CodeController {

    @Autowired
    private Producer producer;

    @GetMapping("/captcha.jpg")
    public void captcha(HttpServletRequest request, HttpServletResponse response)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到 session
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        //将生成的图形验证码放到session中
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("captcha", text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

    @PostMapping("/authImageCode")
    public ResultMsg authCaptcha(@RequestParam String imagecode){
        Session session = SecurityUtils.getSubject().getSession();
        String text = (String) session.getAttribute("captcha");
        if (!text.equals(imagecode.trim())) {
            return ResultMsg.error("图形验证不匹配");
        }
        return ResultMsg.ok();
    }


}
